package com.hs.core.utils;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadfileUtil {

	/**
	 * 上传文件
	 * @param request  HttpServletRequest对象
	 * @param destDir  上传文件保存的路径，例如：D:/work/destdir/
	 * @return         上传后的文件，返回File对象
	 * @throws Exception
	 */
	public File uploadFile(HttpServletRequest request,String destDir) {
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		File destFile = null ;
		if (isMultipart) {   
		    // 创建磁盘工厂，利用构造器实现内存数据储存量和临时储存路径   
		     DiskFileItemFactory factory = new DiskFileItemFactory();   
		    // 设置最多只允许在内存中存储的数据,单位:字节   
		    factory.setSizeThreshold(4096);   
		    // 设置文件临时存储路径   
		     factory.setRepository(new File("D:/work/temp")); 
		     ServletFileUpload upload = new ServletFileUpload(factory);   
		    upload.setHeaderEncoding("UTF-8");   
		    upload.setSizeMax(1024 * 1024 * 100);  
		    // 得到所有的表单域，它们目前都被当作FileItem   
		     List<FileItem> fileItems = null;
			try {
				fileItems = upload.parseRequest(request);
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}   
			File f = new File(destDir);
			if(!f.exists()){
				f.mkdirs();
			}
		    Iterator<FileItem> iter = fileItems.iterator();   
		    while (iter.hasNext()) {   
		        FileItem item = (FileItem) iter.next();   
		        if (item.isFormField()) {   
		            // 如果item是正常的表单域   
		            String name = item.getFieldName();  
		        } else {   
		            // 如果item是文件上传表单域 ,获得文件名及路径   
		            String fileName = item.getName();  
		            if (fileName != null) {
						// 如果文件存在则上传
						destFile = new File(destDir + fileName);
						try {
							item.write(destFile);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}   
		        }   
		    }   
		}  
		return destFile ;
	}
}

